package com.lv.suyiyong.hfr.ui

import android.graphics.Typeface
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SizeUtils
import com.bumptech.glide.Glide
import com.google.android.material.tabs.TabLayoutMediator
import com.lv.common.adapter.FactoryContainerPagerAdapter
import com.lv.common.base.BaseActivity
import com.lv.common.bean.CommonSelectedBean
import com.lv.common.ktx.AppBarState
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.setSelectedTabIndicatorFixWidth
import com.lv.common.ktx.setupAppBarLayoutListener
import com.lv.common.ktx.viewLifeCycleOwner
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.bean.ADBean
import com.lv.service.model.ServiceViewModel
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.category.SpuCategoryBean
import com.lv.service.room.category.SpuCategoryDbHelper
import com.lv.service.utils.YgxAroutPageKt
import com.lv.service.utils.YgxToolsKt
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.adapter.BannerNearGoodsAdapter
import com.lv.suyiyong.hfr.databinding.ActivityNearGoodsTabBinding
import com.lv.suyiyong.hfr.fragment.CouponFactoryTabFragment
import com.lv.suyiyong.hfr.fragment.NearGoodsFragment
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.listener.OnBannerListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * 作者： ygx
 * 创建日期：2023/3/28 5:51 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：附近商品 页面
 */
@Route(path = ARoutUtils.NearGoodsTabActivity)
class NearGoodsTabActivity : BaseActivity<ActivityNearGoodsTabBinding>() {
    private val mBannerTopData = mutableListOf<ADBean>()
    private var mBannerTopAdapter: BannerNearGoodsAdapter? = null

    private var mScrollY = 0
    private val mTopIv =
        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/iOS/projectPic/hfr/localProductNav.png"
    private var mUserInfo: UserInfo? = null
    private val mTabs = mutableListOf<CommonSelectedBean>()
    private var mAdapter: FactoryContainerPagerAdapter? = null

    private val serviceViewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_near_goods_tab
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@NearGoodsTabActivity, viewStatus)
            ivBackPage.setOnClickListener { finish() }
        }
    }


    override fun initConfig() {
        super.initConfig()
        mBinding.ivTitlePage.LoadSrc(mTopIv)
        initBannerAdapter()
        bannerObserver()
        lifecycleScope.launch {
            val taskCategory = async {
                val mAllCategory = getCategoryForDB()
                mTabs.clear()
                mTabs.add(CommonSelectedBean("推荐", postiont = 0, selected = true))
                mAllCategory?.forEach {
                    mTabs.add(CommonSelectedBean(it.name, postiont = it.fcaid))
                }
            }
            taskCategory.await()
            initPage()
        }

        UserDbHelper.getLiveUserInfo(this).observeKt {
            mUserInfo = it
        }
    }

    private suspend fun getCategoryForDB(): List<SpuCategoryBean>? {
        return withContext(Dispatchers.IO) {
            //获取工厂分类
            SpuCategoryDbHelper.getFindAllCategorySuspend(this@NearGoodsTabActivity)
        }
    }

    private fun findAllBanner() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { serviceViewModel.findAllBanner("5") }.await()
            parseBannerResult(result)
        }
    }

    private fun parseBannerResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<List<ADBean>> { code, data, message, result ->
                if (!data.isNullOrEmpty()) {
                    mBannerTopData.clear()
                    mBannerTopData.addAll(data)
                    mBannerTopAdapter?.notifyDataSetChanged()
                    YgxUtilsKt.parseBannerTime(mBinding.banner, mBannerTopData[0].startup)
                }
            }
            onBizError<String> { code, message, data ->
                showToast(message)
            }
        }
    }

    /**
     * 设置Banner适配器
     */
    private fun bannerObserver() {
        mBinding.banner.addBannerLifecycleObserver(viewLifeCycleOwner)
            .setAdapter(mBannerTopAdapter)
            .setIntercept(false)

    }

    /**
     * 初始化轮播图Adapter
     */
    private fun initBannerAdapter() {
        mBannerTopAdapter = BannerNearGoodsAdapter(mBannerTopData)

        mBannerTopAdapter?.setOnBannerListener(OnBannerListener<Any?> { data, position ->
            mBinding.banner.isAutoLoop(false)
            val indexCommon = mBannerTopData[position]
            YgxAroutPageKt.aroutPager(
                this,
                indexCommon.tag,
            )
//            mBannerTopData[position].statistics = -1
        })
    }


    override fun initEvents() {
        super.initEvents()

    }

    override fun initData() {
        super.initData()

    }

    private fun initPage() {
        findAllBanner()
        initViewPager()
    }


    private fun initViewPager() {

        mAdapter = FactoryContainerPagerAdapter(
            supportFragmentManager, lifecycle,
            mTabs
        )
        mAdapter?.listener = object : FactoryContainerPagerAdapter.CirTabListener {
            override fun getFragment(position: Int): Fragment {
                val fragment = NearGoodsFragment.newInstance(mTabs[position].postiont)
                return fragment
            }
        }

        mBinding.viewpager.adapter = mAdapter
        TabLayoutMediator(mBinding.tabLayout, mBinding.viewpager) { tab, position ->
            tab.text = mTabs[position].name
        }.attach()
        mBinding.viewpager.offscreenPageLimit = mTabs.size
        mBinding.tabLayout.setSelectedTabIndicatorFixWidth(SizeUtils.dp2px(19.0f).toFloat())
        mBinding.tabLayout.addOnTabSelectedListener(YgxToolsKt.setSelectedBoldTab())

        val selecTab = mTabs[0].name ?: ""
        val spannedString = YgxToolsKt.setTextSpan(selecTab, Typeface.BOLD)
        mBinding.tabLayout.getTabAt(0)?.text = spannedString
    }


}